package com.hy.jdbc.impl;

import com.hy.entity.Entity;
import com.hy.jdbc.Database;
import com.hy.enums.Dialect;

import java.sql.*;
import java.util.List;
import java.util.Map;

/**
 * 数据库抽象类
 * @author hy
 * @since 2016-11-09
 */
public abstract class AbstractDatabase implements Database {
	
	public static Database newDatabase(Dialect dialect) {
		Database database;
        switch (dialect) {
            case mysql:
            case mariadb:
            case sqlite:
            	database = new MysqlDatabase();
                break;
            case oracle:
            	database = new OracleDatabase();
                break;
            case hsqldb:
            	database = new HsqldbDatabase();
                break;
            case sqlserver:
            	database = new SqlServerDatabase();
                break;
            case sqlserver2012:
            	database = new SqlServer2012Database();
                break;
            case db2:
            	database = new Db2Database();
                break;
            case postgresql:
            	database = new PostgreSQLDatabase();
                break;
            case informix:
            	database = new InformixDatabase();
                break;
            case h2:
            	database = new H2Database();
                break;
            default:
                throw new RuntimeException(dialect + "方言错误!");
        }
        return database;
    }

	/**
	 * 获取jdbc连接
	 * @param driver
	 * @param url
	 * @param user
	 * @param password
	 */
	public static Connection getConnection(String driver, String url, String user, String password){
		Connection conn = null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, password); 
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 关闭jdbc连接
	 * @param rs
	 * @param ps
	 * @param con
	 */
	public static void close(ResultSet rs, PreparedStatement ps, Connection con) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (ps != null) {
				ps.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (con != null) {
				con.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<String> getTablesByDatabase(Map<String, String> xmlMap){
		return null;
	}

    @Override
    public String getTableCommentInfo(Map<String, Object> xmlMap){
	    return "";
    }

	@Override
	public abstract List<Entity> getEntityObjList(Map<String, Object> xmlMap);

}
